package com.dmy.chat.server.netty.handler;

import com.dmy.chat.server.netty.IChannelManager;
import com.dmy.chat.server.netty.UserChannelBind;
import com.dmy.chat.server.netty.message.Messages;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by YCQ for 2020/1/15 10:35
 */
public class DefaultUserChannelBind implements UserChannelBind {
    private static final Map<Object,DefaultUserChannelBind> CACHE_INSTANCE = new ConcurrentHashMap<>();

    private final Map<String, ChannelId> cacheUserChannels ;

    private final IChannelManager channelManager;


    private DefaultUserChannelBind(IChannelManager channelManager) {
        this.channelManager = channelManager;
        cacheUserChannels = new ConcurrentHashMap<>();
    }

    public static  DefaultUserChannelBind getInstance(IChannelManager channelManager,Object key){
        return CACHE_INSTANCE.computeIfAbsent(key, k -> new DefaultUserChannelBind(channelManager));
    }
    public static DefaultUserChannelBind getInstance(IChannelManager channelManager){
        return getInstance(channelManager,DefaultUserChannelBind.class);
    }
    @Override
    public IChannelManager getChannelManager() {
        return channelManager;
    }

    @Override
    public void register(String userId, Channel channel) {
        cacheUserChannels.put(userId,channel.id());
    }

    @Override
    public Channel getUserChannel(String userId) {
        ChannelId channelId = cacheUserChannels.get(userId);
        if(channelId == null){
            return null;
        }
        return channelManager.getClient(channelId);
    }
}
